package MapReduce.Demo1_WordCount;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

/**
 * @Author lixin
 * @Date 2023/3/15 9:09
 */
public class WordCountMapper extends Mapper<LongWritable, Text,Text, IntWritable> {

    Text keyOut = new Text();
    IntWritable valueOut = new IntWritable(1);


    @Override
    protected void setup(Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
        System.out.println("Mapper类里的 setUp 方法");
    }

    /**
     * 进入到 Mapper 类的数据格式
     *      hello world hello
     *      hello hello
     * @param key
     * @param value
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {

        System.out.println("当前行的偏移量："+key.get());
        System.out.println("当前行的内容："+value.toString());

        //把每行的Text类型的内容先转成字符串类型，方便后面的处理
        String line = value.toString();

        //把每行的数据按照空格进行拆分，形成单词的数组
        String[] words = line.split(" ");

        //遍历所有的单词，把每个单词以 键值对的形式 输出
        for (String word : words) {
            keyOut.set(word);
            context.write(keyOut,valueOut);
        }

    }


    @Override
    protected void cleanup(Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
        System.out.println("Mapper类里的 cleanUp 方法");
    }
}
